package com.bk.controller.empsso;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.bk.entity.EmployeeInfo;
import com.bk.entity.RoleInfo;
import com.bk.service.RedisService;
import com.bk.service.empInfo.EmployeeInfoService;
import com.bk.service.log.EmpLogService;
import com.bk.util.JwtUtil;
import com.bk.util.ReturnUtil;
import com.bk.util.SerilizableObjectUtil;
import com.bk.util.TimeUtil;
import com.netflix.discovery.util.StringUtil;

@RestController
public class EmpSsoLoginController {

	@Autowired
	private RedisService redisService;

	@Autowired
	private EmployeeInfoService employeeInfoService;

	@Autowired
	private EmpLogService empLogService;

	/**
	 * 页面登录
	 */
	@PostMapping("/ssoLogin")
	public ReturnUtil<String> login(HttpServletResponse response, @RequestParam("empId") String empId,
			@RequestParam("password") String password, @RequestParam("url") String url,
			@RequestParam("authorityId") String authorityId) {
		/** 返回通行令牌 */
		String token = checkUsernameAndPassword(empId, password, authorityId);
		System.out.println(token + "employee进来了");
		if (!StringUtils.isEmpty(token)) {
			try {
				Cookie cookie = new Cookie("Authorization", token);
				List<String> list = new ArrayList<String>();
				list.add(token);
				cookie.setMaxAge(60 * 3);
				// 设置域
//	                cookie.setDomain("huanzi.cn");
				// 设置访问路径
				cookie.setPath("/");
				response.addCookie(cookie);
				// 重定向到原先访问的页面
				// response.sendRedirect(url);
				return new ReturnUtil<String>(200, "存储令牌信息到redis", list);
			} catch (Exception e) {
				e.printStackTrace();
			}
			return null;
		}
		return new ReturnUtil<String>(404, null, "没有此柜员信息");
	}

	/**
	 * 判断令牌是否存在是否存在
	 */
	@GetMapping("/HasRedisKey/{key}")
	public Boolean hasKey(@PathVariable("key") String key) {
		return redisService.hasRedisKey(key) ? true : false;
	}

	/**
	 * 校验用户名密码，成功则返回通行令牌
	 */
	@PostMapping("/checkUsernameAndPassword")
	private String checkUsernameAndPassword(String empId, String password, String authorityId) {
		// 通行令牌
		long time = System.currentTimeMillis();
		String token="";
		EmployeeInfo employee = employeeInfoService.getEmployeeInfo(empId, password, authorityId);
		if (!StringUtils.isEmpty(employee)) {
			
			// 生成token
			token = JwtUtil.generateToken(employee);
			
			RoleInfo roleInfo = employeeInfoService.getEmployeeRoleVoByAuthority(authorityId);
			 String desc="柜员号为"+employee.getEmployeeId()+"的"+employee.getEname()+roleInfo.getRoleName()+"用户在"+TimeUtil.getCurrentTimeUtil()+"进行签到";
			// 令牌作为key，存用户id作为value（或者直接存储可暴露的部分用户信息也行）设置过期时间
			redisService.setKey("Authorization", token);
			redisService.setKey("employInfo", SerilizableObjectUtil.serialize(employee));
			redisService.setKey("authorityId", String.valueOf(authorityId));
			empLogService.createEmpSignLog(TimeUtil.getCurrentTimeUtil(), employee.getEname(), employee.getEmployeeId(),
					roleInfo.getRoleName(), desc);
		}
		return token;
	}

	@GetMapping("/exitout") /** 签退 */
	private ReturnUtil<String> exitout(HttpServletResponse res) {
		List<String> list = null;
		redisService.deleteRedisByKey("authorityId");
		redisService.deleteRedisByKey("Authorization");
		redisService.deleteRedisByKey("employInfo");
		Cookie killMyCookie = new Cookie("Authorization", null);
		killMyCookie.setMaxAge(0);
		killMyCookie.setPath("/");
		res.addCookie(killMyCookie);
		return new ReturnUtil<>(200, "签退成功", list);
	}
	
	
	@GetMapping("/redirctLogin") /** 重定向到登录页 */
	private ReturnUtil<String> redirctLogin() {
		return new ReturnUtil<>(401,"", "用户未登录");
	}

}
